import numpy as np
from PIL.Image import Image
from skfuzzy import control as ctrl
from skfuzzy import membership
from PIL import Image
import matplotlib.pyplot as plt
# 定义ANFIS结构
import random

class ANFIS:
    def __init__(self):
        # 定义输入和输出变量
        self.input1 = ctrl.Antecedent(np.arange(0, 10, 1), 'input1')
        self.input2 = ctrl.Antecedent(np.arange(0, 10, 1), 'input2')
        self.output = ctrl.Consequent(np.arange(0, 100, 1), 'output')

        # 定义模糊集合
        self.input1.automf(5)  # 输入模糊集合
        self.input2.automf(5)
        self.output['very_low'] = membership.trimf(self.output.universe, [0, 0, 25])
        self.output['low'] = membership.trimf(self.output.universe, [0, 25, 50])
        self.output['medium'] = membership.trimf(self.output.universe, [25, 50, 75])
        self.output['high'] = membership.trimf(self.output.universe, [50, 75, 100])
        self.output['very_high'] = membership.trimf(self.output.universe, [75, 100, 100])

        # 随机生成规则
        self.rules = self.generate_random_rules(10)  # 生成10条随机规则
        self.control_system = ctrl.ControlSystem(self.rules)
        self.simulator = ctrl.ControlSystemSimulation(self.control_system)

    def generate_random_rules(self, num_rules):
        rules = []
        inputs1_terms = self.input1.terms.keys()
        inputs2_terms = self.input2.terms.keys()
        outputs_terms = self.output.terms.keys()

        for _ in range(num_rules):
            input1_term = random.choice(list(inputs1_terms))
            input2_term = random.choice(list(inputs2_terms))
            output_term = random.choice(list(outputs_terms))
            rules.append(ctrl.Rule(self.input1[input1_term] & self.input2[input2_term], self.output[output_term]))

        return rules

    def evaluate(self, x1, x2):
        self.simulator.input['input1'] = x1
        self.simulator.input['input2'] = x2
        self.simulator.compute()
        return self.simulator.output['output']


# 定义卷积操作
def convolve_with_anfis(image, anfis_model, kernel_size=3, stride=1, padding=0):
    if kernel_size % 2 == 0:
        raise ValueError("Kernel size must be odd.")

    # 图像填充
    padded_image = np.pad(image, padding, mode='constant')
    output_shape = ((padded_image.shape[0] - kernel_size) // stride + 1,
                    (padded_image.shape[1] - kernel_size) // stride + 1)
    output_image = np.zeros(output_shape)

    for i in range(0, padded_image.shape[0] - kernel_size + 1, stride):
        for j in range(0, padded_image.shape[1] - kernel_size + 1, stride):
            region = padded_image[i:i + kernel_size, j:j + kernel_size]
            # 使用ANFIS处理当前区域
            output_image[i // stride, j // stride] = anfis_model.evaluate(np.mean(region), np.std(region))

    return output_image

# 测试代码
if __name__ == '__main__':
    # 创建ANFIS模型
    anfis_model = ANFIS()

    image_path = 'images.jpg'  # 替换为你的彩色图像路径
    color_image = Image.open(image_path)  # 打开图像
    test_image = np.array(color_image)  # 转换为numpy数组

    # 打印图像的形状

    # 测试图像
 #    test_image = [[7.45880199,7.84170605, 8.15565654, 6.56894306 ,2.67095349],
 # [1.97273134 ,9.0591591 ,7.37383152, 1.94890537 ,8.35874968],
 # [5.34412868 ,7.54527945 ,7.71361454 ,8.93041258 ,4.39612928],
 # [3.93321893 ,2.20671553 ,9.63942031 ,3.70206885 ,4.02537812],
 # [7.16656248 ,7.29098332 ,7.91095554 ,0.05625537 ,0.41002426]]
 #    image_path ="images.jpg"
 #    test_image = Image.open(image_path).convert('L')  # 转换为灰度图像
 #    test_image = np.array(test_image)
    # 卷积
    print(test_image)
    kernel_size = 3 # 可以调整卷积核大小
    result_image = convolve_with_anfis(test_image, anfis_model, kernel_size=kernel_size, stride=1, padding=1)
    print("result")
    print(result_image)
    # 可视化结果
    plt.figure(figsize=(8, 4))
    plt.subplot(1, 2, 1)
    plt.title('原始图像')
    plt.imshow(test_image, cmap='gray', vmin=0, vmax=10)
    plt.colorbar()

    plt.subplot(1, 2, 2)
    plt.title('卷积后的图像')
    plt.imshow(result_image, cmap='gray', vmin=0, vmax=100)
    plt.colorbar()

    plt.show()
